package com.jiadakeji.ppm.api.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiadakeji.ppm.common.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class ApiFilter extends AccessControlFilter {
	public static final String KEY = "zhangfen";

	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (isLoginRequest(request, response)) {
			return true;
		}
		// String token = request.getParameter("token");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String token = httpRequest.getHeader("token");
		String timestamp = httpRequest.getHeader("timestamp");
		String sign = httpRequest.getHeader("sign");
		if (StringUtils.isBlank(token) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(sign)) {// 非法请求
			return false;
		}
		// 1、判断token是否存在，暂时不管，因为不管是从数据库查询还是缓存到redis，都影响效率
//		if(JedisUtils.get(token) == null){
//			return false;
//		}
		
		// 2、判断时间戳是否在当前5分钟内，防止重放攻击
		//FIXME  接口测试期，先取消，部署后启用
//		Date requestDate = new Date(Long.parseLong(timestamp));
//		Date now = new Date();
//		if(now.after(DateUtils.addMinutes(requestDate, 5))){
//			return false;
//		}

		// 3、判断签名是否合法
		String input = token + timestamp + KEY;
		String check = new String(DigestUtils.md5Hex(input));
		if (sign.equals(check)) {
			return true;
		}
		return false;

	}

	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setStatus(HttpServletResponse.SC_OK);
		JsonResult<String> result = new JsonResult<String>(401, "授权失败");
		ObjectMapper objectMapper = new ObjectMapper();
		httpResponse.getWriter().write(objectMapper.writeValueAsString(result));
		return false;
	}
}